<template>
    <div  :class="[listType=='text'?'':'list_upload']" class="tl add_prod_img">
        <el-row>
            <el-col :span="24"  >
                <ul class="el-upload-list el-upload-list--picture-card" v-if="!isOneImg">   
                    <li class="el-upload-list__item is-success zu" v-for="(item,index) in fileList" :class="{zhuTu:zhuIndex===index}" :key="index">
                        <img :src="$fnc.getImgUrl(item.url)" alt="" class="el-upload-list__item-thumbnail">
                        <a class="el-upload-list__item-name">
                            <i class="el-icon-document"></i>
                        </a>
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview">
                                <i @click="detailsImg(item)" class="el-icon-zoom-in"></i>
                            </span>
                            <span class="el-upload-list__item-delete">
                                <i @click="deleteImg(item,index)" class="el-icon-delete"></i>
                            </span>
                        </span>
                        <el-progress v-if="item.imgPercent<100" class="video_jindu_shop" type="circle" :percentage="item.imgPercent"></el-progress>
                    </li>
                </ul>

                <span>
                    <el-upload ref="uploadxls"
                        class="setZhutu" :action="imgServe"
                        :list-type="listType"
                        :on-progress="progessimg"       
                        :file-list="fileList" 
                        :data="{
                            folder:folder
                        }"
                        :on-success="uploadSuccess"
                        :show-file-list="false"
                        :before-upload="beforeupload">
                         <el-progress
                            v-if="isOneImg && imgFlag == true && listType!='text'"
                            class="img_progess"
                            type="circle"
                            :percentage="imgUploadPercent"
                        ></el-progress>  
                        <img v-if="isOneImg && piclink && listType!='text'" :src="$fnc.getImgUrl(piclink)" class="avatar">
                        <el-button  :loading='$store.state.isLoading' v-else-if="listType=='text' && !wx" size="small" type="primary" >点击上传</el-button>
                        <span v-else-if="wx && !wxmenu">图片</span>
                        <i v-else-if="wxmenu"  class="icon_msg_sender tips imgnav-select"  :class="{upImg_active : wxmenu}"></i>
                        <i v-else class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible" :append-to-body="true" v-if="!isOneImg">
                        <img width="100%" :src="$fnc.getImgUrl(dialogImageUrl)" alt="">
                    </el-dialog>
                </span>
                
            </el-col>
        </el-row>
         <!-- vueCropper 剪裁图片实现-->
        <el-dialog   top="20px" title="图片剪裁" :modal="false"  :visible.sync="dialogimg" width="400px" >
            <div class="cropper-content">
                <div class="cropper" style="text-align:center">
                <vueCropper
                    ref="cropper"
                    :img="crooption.img"
                    :outputSize="crooption.size"
                    :outputType="crooption.outputType"
                    :info="true"
                    :full="crooption.full"
                    :canMove="crooption.canMove"
                    :canMoveBox="crooption.canMoveBox"
                    :original="crooption.original"
                    :autoCrop="crooption.autoCrop"
                    :fixed="crooption.fixed"
                    :fixedNumber="crooption.fixedNumber"
                    :centerBox="crooption.centerBox"
                    :infoTrue="crooption.infoTrue"
                    :fixedBox="crooption.fixedBox"               
                ></vueCropper>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button  :loading='$store.state.isLoading' @click="dialogimg = false">取 消</el-button>
                <el-button  :loading='$store.state.isLoading' type="primary" @click="finish" >确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import axios from 'axios';
export default {
    props:{
       files:{  //文件列表
         type: Array,
         default:()=>{return []}
       },
       iszhutu:{ //是否主图
           type:Boolean,
           default:false
       },
       onSuccess:Function,
       onRemove:Function,
       isOneImg:{
           type:Boolean, //是否单图
           default:true
       },
       listType:{   //上传组件的样式
           type:String,
           default:'picture-card'
       },
       imgServe:{
           type:String,
           default:"/api/common/upload/index/"
       },
       wx:{
           type:Boolean,
           default:false
       },
       wxmenu:{
           type:Boolean,
           default:false
       },
       pic:{
           type:String,
           default:""
       },
       isCropper:{
           type:Boolean,
           default:true
       },
       folder:{
           type:String,
           default:"banner"
       },
       skuId:[String,Number],
       isGzip:{
           type:Boolean,
           default:true
       }
    },
    data(){
        return{
            dialogimg: false,
            dialogImageUrl:"",
            fileList:this.files,
            dialogVisible:false,
            piclink:this.pic,
            zhuIndex:-1,
            imgQuality: 0.1862, //图片质量
            imgFlag:false,
            imgUploadPercent:"0",
            crooption: {
                 img: '',                         // 裁剪图片的地址
                info: true,                      // 裁剪框的大小信息
                outputSize: 1,                   // 裁剪生成图片的质量
                outputType: 'png',               // 裁剪生成图片的格式
                canScale: false,                 // 图片是否允许滚轮缩放
                autoCrop: true,                  // 是否默认生成截图框
                autoCropWidth: '',              // 默认生成截图框宽度
                autoCropHeight: '',             // 默认生成截图框高度
                fixed: true,                    // 是否开启截图框宽高固定比例
                fixedNumber: [4, 4],   
                          // 截图框的宽高比例
                full:true,
                original: false, // 上传图片按照原始比例渲染
                 infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
                 centerBox:true             // 截图框的宽高比例
            },
        }
    },
    methods:{
        dataURItoBlob(dataURI, type) {
            var binary = atob(dataURI.split(',')[1]);
            var array = [];
            for(var i = 0; i < binary.length; i++) {
                array.push(binary.charCodeAt(i));
            }
            return new Blob([new Uint8Array(array)], {type: type});
            
        },
        beforeupload(file){
            console.log(1)
            if(this.isCropper){
                this.$nextTick(() => {
                    this.crooption.img= URL.createObjectURL(file);
                    this.dialogimg = true;
                })      
                return false;
            }else if(this.isGzip){
                console.log(11)
                const imgSize = file.size / 1024 / 1024
                if(imgSize > 1) {
                    const _this = this
                    return new Promise(resolve => {
                    var reader = new FileReader()
                    var image = new Image()
                    image.onload = (imageEvent) => {
                        var canvas = document.createElement('canvas');
                        var context = canvas.getContext('2d');
                        var canvas = document.createElement('canvas');
                        var context = canvas.getContext('2d');
                        var width = image.width * _this.imgQuality
                        var height = image.height * _this.imgQuality

                        canvas.width = width;
                        canvas.height = height;
                        context.clearRect(0, 0, width, height);
                        context.drawImage(image, 0, 0, width, height);
                        var dataUrl = canvas.toDataURL(file.type);
                        var blobData = _this.dataURItoBlob(dataUrl, file.type);
                        resolve(blobData)
                    }
                        reader.onload = (e => { image.src = e.target.result; });
                        reader.readAsDataURL(file);
                    })
                }
            }
            
        },
        progessimg(event, file, fileList){
            if(this.isOneImg){
                this.imgFlag = true;
                this.imgUploadPercent = parseInt(event.percent);
            }else{
                file.iszhutu=false;
                file.imgPercent=parseInt(event.percent);            
                this.fileList=fileList;
            }
                  
        },
        finish() {
            var that=this;
            this.$refs.cropper.getCropData(data => {
            this.dialogimg = false
            // 先将显示图片地址清空，防止重复显示
            this.crooption.img = ''
            // var reader = new FileReader();
                //创建一个img对象
            var  img = new Image();

            img.src = data
            // base64地址图片加载完毕后执行
            img.onload = function () {
                // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');
                // 图片原始尺寸
                var originWidth = this.width;
                var originHeight = this.height;
                // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
                var maxWidth = 750,
                    maxHeight = 750;
                // 目标尺寸
                var targetWidth = originWidth,
                    targetHeight = originHeight;
                // 图片尺寸超过最大尺寸的限制
                if(originWidth > maxWidth || originHeight > maxHeight) {
                    if(originWidth / originHeight > maxWidth / maxHeight) {
                        // 更改宽度，按照宽度限定尺寸
                        targetWidth = maxWidth;
                        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                    } else {
                        targetHeight = maxHeight;
                        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                    }
                }
                //对图片进行缩放
                canvas.width = targetWidth;
                canvas.height = targetHeight;
                // 清除画布
                context.clearRect(0, 0, targetWidth, targetHeight);
                // 图片压缩
                context.drawImage(img, 0, 0, targetWidth, targetHeight);
                /*第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/
                //压缩后的base64文件
                var newUrl = canvas.toDataURL('image/jpeg', 0.92);
                let file = that.convertBase64UrlToBlob(newUrl)
                var fd = new FormData();
                fd.append("file", file,"file_"+Date.parse(new Date())+".jpg");
                fd.append("folder",that.folder );
                 axios.post('/api/common/upload/index/', fd).then(res => {
                        if(res.data.code==200 && that.isOneImg){
                            that.piclink=res.data.result;
                            that.imgFlag = false;
                            that.imgUploadPercent = 0;
                        }else if(res.data.code==400){
                            that.$message.error("上传失败！不支持的类型")
                        }
                        if(that.isOneImg){
                            console.log(11)
                            that.onSuccess(res.data.result,that.skuId);
                        }else{
                            console.log(22)
                            var params={};
                                params.uid=0;
                                params.url=res.data.result
                            that.onSuccess(params,that.skuId)
                        }
            })
            }
        })
        },
        convertBase64UrlToBlob(urlData) {
            let bytes = window.atob(urlData.split(',')[1]);//去掉url的头，并转换为byte
            //处理异常,将ascii码小于0的转换为大于0
            let ab = new ArrayBuffer(bytes.length);
            let ia = new Uint8Array(ab);
            for (var i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
            }
            return new Blob([ab], { type: 'image/png' });
        },
        deleteImg(item,index){
            var _this=this;
             this.$confirm('确定删除吗, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {

                    if(this.zhuIndex==index){
                        this.zhuIndex=-1;
                    }
                        const currRow = _this.fileList.splice(index, 1)[0];
                    var id=item.id || '0';
                    if(id=='0'){
                        _this.$message.success('删除成功');          
                    }else{
                        this.onRemove(...arguments,item)
                    }
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
                });
        },
        detailsImg(item){
            console.log(item)
            this.dialogVisible=true;
            this.dialogImageUrl=item.url;
        },
        setZhutu(item,index){
            this.zhuIndex=index;
            if(item.id==undefined && item.response==undefined)return false;
            if(item.id==undefined){
                // this.shopInfo.piclink=item.response.result;
            }else{
                // this.shopInfo.piclink=item.url;
            }
        },
        uploadSuccess(response){
            if(response.code==200 && this.isOneImg){
                this.piclink=response.result;
                this.imgFlag = false;
                this.imgUploadPercent = 0;
            }else if(response.code==400){
                this.$message.error("上传失败！不支持的类型")
            }
            if(this.isOneImg){
                this.onSuccess(response.result,this.skuId);
            }else{
                this.onSuccess(...arguments,)
            }
           ;
        },
    },
    watch:{
        pic(val1,val2){
            this.piclink='';
            this.piclink=val1;
        },
        files(val){
            this.fileList=val;
        }
    }
}
</script>